package com.longyiqun.android.zhihu.Activity;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AbsListView;
import android.widget.AdapterView;

import com.dd.CircularProgressButton;
import com.etsy.android.grid.StaggeredGridView;
import com.longyiqun.android.zhihu.Adapter.MyGridViewAdapter;
import com.longyiqun.android.zhihu.Object.Case;
import com.longyiqun.android.zhihu.R;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import java.io.InputStream;
import java.util.ArrayList;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

public class CakeActivity extends BaseActivity implements AbsListView.OnScrollListener, AbsListView.OnItemClickListener {

    // Activity之间传值使用
    public final static String EXTRA_MESSAGE = "com.longyiqun.android.zhihu.Activity";
    // 定义一个瀑布的gridview
    private StaggeredGridView mGridView;
    // 是否需要加载更多
    private boolean mHasRequestedMore;
    // 瀑布gridview的Adapter
    private MyGridViewAdapter mAdapter;
    // 瀑布gridview的data
    private ArrayList<String> mData;
    private ArrayList<Case> caseData;
    // Debug用
    //private static final String TAG = "StaggeredGridActivity";
    // Save Data Key
    //public static final String SAVED_DATA_KEY = "SAVED_DATA";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView2(R.layout.activity_cake);
        // 添加loading按钮
        final CircularProgressButton cpb = (CircularProgressButton) findViewById(R.id.cpb);
        cpb.setProgress(0);

        // 显示返回上层按钮
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        // 获得GridView
        mGridView = (StaggeredGridView) findViewById(R.id.grid_view);
        // 获得GridView的Adapter
        mAdapter = new MyGridViewAdapter(this, R.id.txt_desc);
        // 判断是否有储存的数据
        /*if (savedInstanceState != null) {
            mData = savedInstanceState.getStringArrayList(SAVED_DATA_KEY);
        }*/
        // 判断是否有填充数据，如果没有，则去取data
        if (mData == null) {
            caseData = new ArrayList<Case>();
            try {
                InputStream stream = getAssets().open("cases.xml");
                DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
                DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
                Document doc = dBuilder.parse(stream);
                Element root = doc.getDocumentElement();
                NodeList items = root.getElementsByTagName("case");
                for (int i = 0; i < items.getLength(); i++) {
                    Node item = items.item(i);
                    Element eElement = (Element) item;
                    int id = Integer.parseInt(eElement.getElementsByTagName("id").item(0).getTextContent());
                    String desc = eElement.getElementsByTagName("desc").item(0).getTextContent();
                    String url = eElement.getElementsByTagName("url").item(0).getTextContent();
                    String params = eElement.getElementsByTagName("params").item(0).getTextContent();
                    String headers = eElement.getElementsByTagName("headers").item(0).getTextContent();
                    String type = eElement.getElementsByTagName("type").item(0).getTextContent();
                    Case c = new Case();
                    c.setDesc(desc);
                    c.setHeaders(headers);
                    c.setId(id);
                    c.setParams(params);
                    c.setUrl(url);
                    c.setType(type);
                    caseData.add(c);
                }

            } catch (Exception ex) {
                System.out.println(ex.getMessage());
            }
        }
        // 把数据添加到Adapter
        for (Case data : caseData) {
            mAdapter.add(data);
        }
        // 设置gridview
        mGridView.setAdapter(mAdapter);
        mGridView.setOnScrollListener(this);
        mGridView.setOnItemClickListener(this);
    }

    // 点击每一个Item事件
    @Override
    public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
        Case c = (Case) adapterView.getAdapter().getItem(position);
        if (c.isRun() != false && c.getResult() != "") {
            //Toast.makeText(this, "Item Clicked: " + c.getResult(), Toast.LENGTH_SHORT).show();

            // 意图 -> WebViewActivity
            Intent intent = new Intent(this, CaseResultActivity.class);
            // Result的传递
            intent.putExtra(EXTRA_MESSAGE, c.getResult());
            // 开启意图
            startActivity(intent);
        }
    }

    // 滑动状态改变Listener
    @Override
    public void onScrollStateChanged(final AbsListView view, final int scrollState) {
        //Log.d(TAG, "onScrollStateChanged:" + scrollState);
    }

    // 滑动Listener
    @Override
    public void onScroll(final AbsListView view, final int firstVisibleItem, final int visibleItemCount, final int totalItemCount) {
        //Log.d(TAG, "onScroll firstVisibleItem:" + firstVisibleItem + " visibleItemCount:" + visibleItemCount + " totalItemCount:" + totalItemCount);
        // 滑到底部，是否添加更多，暂时不需要
        /*if (!mHasRequestedMore) {
            int lastInScreen = firstVisibleItem + visibleItemCount;
            if (lastInScreen >= totalItemCount) {
                Log.d(TAG, "onScroll lastInScreen - so load more");
                mHasRequestedMore = true;
                onLoadMoreItems();
            }
        }*/
    }
    // 加载更多Item, 暂时不需要
    /*private void onLoadMoreItems() {
        final ArrayList<String> sampleData = MyGridViewData.generateSampleData();
        for (String data : sampleData) {
            mAdapter.add(data);
        }
        // stash all the data in our backing store
        mData.addAll(sampleData);
        // notify the adapter that we can update now
        mAdapter.notifyDataSetChanged();
        mHasRequestedMore = false;
    }*/
}